package net.sunxiaolong.tool.captureinsureknowledge.tool;

import org.springframework.util.StringUtils;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.SocketException;
import java.net.URL;
import java.time.LocalDateTime;

/**
 * @author 晓龙
 * @create 2018-08-07 下午3:47
 * @desc
 **/
public class NetworkTool {

    public static String getStringFromUrl(String urlStr, String charset) {
        if (StringUtils.isEmpty(charset)) {
            charset = "UTF-8";
        }
        try {
            URL url = new URL(urlStr);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setDoInput(true);
            connection.connect();
            while (true) {
                try {
                    while (connection.getResponseCode() != HttpURLConnection.HTTP_OK) {
                        connection.disconnect();
                        connection = (HttpURLConnection) url.openConnection();
                        connection.setDoInput(true);
                        connection.connect();
                    }
                    break;
                } catch (SocketException se) {
                    connection.disconnect();
                    System.err.println(LocalDateTime.now().toLocalTime() + "\tURL:" + urlStr + "\t" + se.getMessage());
                    connection = (HttpURLConnection) url.openConnection();
                    Thread.sleep(5000);
                    connection.connect();
                }
            }
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            InputStream is = connection.getInputStream();
            byte[] readByteArray = new byte[2048];
            int readLength = 0;
            while ((readLength = is.read(readByteArray)) != -1) {
                baos.write(readByteArray, 0, readLength);
            }
            is.close();
            baos.close();
            connection.disconnect();
            return new String(baos.toByteArray(), charset);
        } catch (MalformedURLException e) {
            return "";
        } catch (IOException | InterruptedException e) {
            e.printStackTrace();
            return "";
        }
    }
}
